import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.Scanner;
import java.util.Collections;
import java.util.Comparator;

public class LetterFrequency {
    public static void main(String[] args) {
    	System.out.println("当前程序查找文件的路径：" + new File("").getAbsolutePath());
    	// 检查命令行参数
        if (args.length != 2 || !args[0].equals("-c")) {
            System.out.println("用法：wf.exe -c <file name>");
            return;
        }
        String fileName = args[1];
        File file = new File(fileName);
        Map<Character, Integer> letterCount = new HashMap<>();
        int totalLetters = 0;

        // 初始化26个小写字母计数为0
        for (char c = 'a'; c <= 'z'; c++) {
            letterCount.put(c, 0);
        }

        // 读取文件统计字母
        try (Scanner scanner = new Scanner(file)) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine().toLowerCase();
                for (char c : line.toCharArray()) {
                    if (c >= 'a' && c <= 'z') {
                        letterCount.put(c, letterCount.get(c) + 1);
                        totalLetters++;
                    }
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在：" + fileName);
            return;
        }

        // 排序：频率降序，同频率字典序升序
        ArrayList<Map.Entry<Character, Integer>> sortedList = new ArrayList<>(letterCount.entrySet());
        Collections.sort(sortedList, new Comparator<Map.Entry<Character, Integer>>() {
            @Override
            public int compare(Map.Entry<Character, Integer> a, Map.Entry<Character, Integer> b) {
                int freqCompare = b.getValue().compareTo(a.getValue());
                if (freqCompare != 0) {
                    return freqCompare;
                } else {
                    return a.getKey().compareTo(b.getKey());
                }
            }
        });

        // 输出频率（保留两位小数）
        for (Map.Entry<Character, Integer> entry : sortedList) {
            double frequency = (double) entry.getValue() / totalLetters * 100;
            System.out.printf("%c: %.2f%%\n", entry.getKey(), frequency);
        }
    }
}